/**
 * @desc: 下拉区域多选组件
 * @values: {string} 当前选择的省，中文名字符串，英文逗号分隔
 * @handleOk: {func} 确定回传的事件
 */
import React, { useState, useEffect } from 'react';
import { Input, Popover, Checkbox, Button, Divider, Empty } from 'antd';
import styles from './index.module.less';
import { getAllProvince } from '@/services/common';
import { cloneDeep, pull } from 'lodash';

const getValue = val => {
  const arr = val ? val.split(',') : [];
  return arr;
}

export default ({ values, handleOk=null }) => {

  const [ selectArr, setSelectArr ] = useState(getValue(values));
  const [ data, setData ] = useState([]);
  const [ visible, setVisible ] = useState(false);
  const [ value, setValue ] = useState(values);

  //重置选择
  const handleCancel = () => {
    setSelectArr([]);
  }

  //点击确定，数据回传，关闭选择框
  const handleSubmit = () => {
    const val = selectArr.join(',');
    handleOk && handleOk(val);
    if(val) {
      setValue(val);
    } else {
      setValue(undefined);
    }
    setVisible(false);
  }

  //初始加载省数据
  useEffect(() => {
    getProvinceData();
  }, [])

  //请求省数据
  const getProvinceData = async () => {
    const res = await getAllProvince();
    if(res.success) {
      setData(res.data);
    }
  }

  //点击选择省事件
  const handleChecked = (e, name) => {
    if(e.target.checked) {
      const arr = cloneDeep(selectArr);
      arr.push(name);
      setSelectArr(arr);
    } else {
      const arr = cloneDeep(selectArr);
      pull(arr, name);
      setSelectArr(arr);
    }
  }

  //通过state控制弹框展示
  const handleVisibleChange = val => {
    setVisible(val);
    if(val) {
      setSelectArr(getValue(values));
      setValue(values);
    }
  }

  const content = (
    <div style={{ width: '401px' }}>
      {
        data.length > 0 ? 
        <>
          <div>
            {
              data.map((v, index) =>(
                <Checkbox checked={selectArr.includes(v.name)} onChange={e => handleChecked(e, v.name)} style={{ width: '96px', margin: '4px 2px'}} key={v.id}>{v.name}</Checkbox>
              ))
            }
          </div>
          <Divider style={{ margin: '12px 0'}}/>
          <div style={{ textAlign: 'right' }}>
            <Button onClick={handleSubmit} type="primary" style={{ marginRight: '12px' }}>确定</Button>
            <Button onClick={handleCancel}>重置</Button>
          </div>
        </>
        : 
        <Empty />
      }
     
    </div>
  );
  
  return (
    <div className={styles.wrap}>
      <Input className={styles.input} value={value} placeholder="请选择收获地区" />
      <Popover
        overlayStyle={{ padding: 0 }} 
        placement="bottomLeft" 
        content={content} 
        overlayClassName="select-area-common" 
        trigger="click"
        visible={visible}
        onVisibleChange={handleVisibleChange}
      >
        <div className={styles.mask}></div>
      </Popover>
    </div>
  )
}